//
//  QLoginFlutterPlugin.swift
//  Runner
//
//  Created by Zhuk on 2021/6/8.
//

import UIKit

import AuthenticationServices

class QLoginFlutterPlugin: NSObject, FlutterPlugin, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
   
    
    static let instance = QLoginFlutterPlugin()
    
    static func register(with registrar: FlutterPluginRegistrar) {

        let channel = FlutterMethodChannel.init(name: "login", binaryMessenger: registrar.messenger())
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    var resultLogin : FlutterResult?
    
    func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if call.method.elementsEqual("login_apple") {
            if #available(iOS 13.0, *) {
                
                resultLogin = result
                
                let request = ASAuthorizationAppleIDProvider().createRequest()
                
                request.requestedScopes = [.fullName, .email]
                 
                let authController = ASAuthorizationController(authorizationRequests: [request])
                
                authController.delegate = self
                authController.presentationContextProvider =  self
                authController.performRequests()//启动授权
            }
        }
    }
    
    
    @available(iOS 13.0, *)
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return UIApplication.shared.keyWindow!
    }
    
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential else {
           
            return
        }
      
        let params = ["openId": credential.user]
        
        resultLogin?(params)
    }
    
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        
    }

}
